/*
 * This file is part of algowala.
 *
 * algowala is copyright (c) 2012 Jagannathan Sampath <algowala@jagernot.com>
 *
 * algowala is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * algowala is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with algowala.  If not, see <http://www.gnu.org/licenses/>.
 *
*/

#include "tokenizer.h"
#include "command.h"
#include "tcl_interp.h"
#include "ansi_color_codes.h"
#include <iostream>
#include <stdlib.h>
#include <stdint.h>

using namespace std;

extern cmdlist cmdlst;

void add_commands (Tcl_Interp* ti);

int tcl_run (ClientData cd, Tcl_Interp* ti, int objc, Tcl_Obj* CONST objv[]) {

  command* cmdp = cmdlst.cmds [(intptr_t)cd];

  if (cmdp) {

    cmdlst.result = "";

    vector<string> args;
    for (int i = 1; i < objc; ++i) args.push_back (Tcl_GetString(objv[i]));
    tokenizer tz (args);
    cmdp->operator() (tz);

    /*Tcl_Obj* obj = Tcl_NewStringObj (cmdlst.result.c_str(), -1);
    Tcl_SetObjResult (ti, obj);*/

    Tcl_SetResult (ti, (char *) cmdlst.result.c_str(), TCL_STATIC);

  }

  return 0;
}

tcl_interp::tcl_interp () {

  cout << DOING << "*** creating Tcl interpreter ***" << ENDL;
  interp = Tcl_CreateInterp ();
  if (!interp) {
    cout << FAIL << "!!! Could not create Tcl interpreter !!!" << ENDL;
    exit (1);
  }

  Tcl_Init (interp);

  add_commands (interp);

  cout << PASS << "+++ created Tcl interpreter +++" << ENDL;


}

tcl_interp& tcl_interp::operator () (const string& cmd) {

  Tcl_Obj* script = Tcl_NewStringObj (cmd.c_str(), -1);
  Tcl_IncrRefCount (script);
    Tcl_EvalObjEx (interp, script, 0);
  Tcl_DecrRefCount (script);

  result = Tcl_GetStringResult (interp);

  return *this;

}

tcl_interp::~tcl_interp () {

  if (interp) {
    Tcl_DeleteInterp (interp);
  }

}
